<?php

namespace App\Jobs;

use App\Events\RepayMentEvent;
use App\Exceptions\GeneralException;
use App\Models\RepayRecord;
use App\Models\UserGlobal;
use Carbon\Carbon;
use Exception;
use App\Constant\QueueKey;
use App\Constant\ThirdMoneyCode;
use App\Facades\MoneyPlatformRequestFacade;
use App\Models\RepayRecordMonth;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Events\CollectionReceiptEvent;

class RepayMonthJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 300; //秒数

    /**
     * @var
     */
    protected $record_month_id;

    /**
     * RepayMonthJob constructor.
     * @param $record_month_id
     */
    public function __construct($record_month_id)
    {
        $this->onQueue(QueueKey::QUEUE_REPAY_MONTH_RESULT);
        $this->record_month_id = $record_month_id;
    }

    /**
     * Description: Execute the job.
     * Author: Gxs
     * @return void
     */
    public function handle()
    {
        $month = RepayRecordMonth::find($this->record_month_id);
        if (RepayRecordMonth::STATUS_TWO == $month->status) {
            //月保费为0 直接成功
            if( $month->amount == 0 ) {
                //成功
                Log::debug('repay_get_month_result', ['message' => '处理成功']);
                $this->_success($month);
                return;
            }
            if (empty($month->third_record_id)) {
                Log::debug('repay_get_month_result', ['message' => 'third_record_id为空,不能请求三方接口']);
                $this->delete();
                return ;
            }
            $result = MoneyPlatformRequestFacade::getMonthRepayResult([
                'third_record_id' => $month['third_record_id'],
                'trade_no' => $month['trade_no'],
            ]);
            $data = $result['data'];
            if (ThirdMoneyCode::RESULT_STATUS_SUCCESS == $data['resultStatus']) {
                //成功
                $this->_success($month);
                Log::debug('repay_get_month_result', ['message' => '处理成功']);
            } else if (ThirdMoneyCode::RESULT_STATUS_FAILURE == $data['resultStatus']) {
                //失败
                $this->_failure($month, $data);
                Log::debug('repay_get_month_result', ['message' => '处理失败']);
            } else if (ThirdMoneyCode::RESULT_STATUS_FAILURE == $data['resultStatus']) {
                //处理中
                Log::debug('repay_get_month_result', ['message' => '处理中']);
            } else {
                //未捕获结果
                Log::debug('repay_get_month_result', ['message' => '未捕获结果']);
            }
            $this->delete();
        }
        return ;
    }

    /**
     * 要处理的失败任务。
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(Exception $exception){}

    /**
     * Description:
     * Author: Gxs
     * @param RepayRecordMonth $model
     */
    private function _success($model)
    {
        try {
            DB::beginTransaction();
            if (0 == $model->period) {
                //全部还清
                //本队列对应的公共表
                $model::where([
                    ['summary_id', '=', $model->summary_id],
                    ['status', '<>', $model::STATUS_FOUR],
                ])->update([
                    'amount' => 0, //提前结清的月保费0
                    'status' => $model::STATUS_FOUR,
                    'status_time' => Carbon::now(),
                ]);
            } else {
                //单期还清
                //本队列对应的公共表
                $model->update([
                    'status' => $model::STATUS_FOUR,
                    'status_time' => Carbon::now(),
                ]);
            }
            DB::commit();
            //催收更新分案后的案件
            event(new RepayMentEvent($model->summary_id));
            //调用公共接口队列
            RepayCommonJobQueue::dispatch($model->record_id);
        } catch (\Exception $e) {
            DB::rollBack();
        }
    }

    /**
     * Description: 月报失败处理
     * Author: Gxs
     * @param RepayRecordMonth $month
     * @param $data
     * @return bool
     * @throws GeneralException
     */
    private function _failure($month, $data)
    {
        try {
            //如果是代扣Api调用对应事件
            if($month->record->apply_number){
                event(new CollectionReceiptEvent($month->record_id));
            }

            DB::beginTransaction();
            //月报表更新失败状态
            $month->where('id', $month->id)->update([
                'status' => $month::STATUS_THREE,
                'failure' => $data['resultRemark'],
                'status_time' => Carbon::now()
            ]);
            //记录总表更新失败理由
            $record = [
                'status' => RepayRecord::STATUS_THREE,
                'failure_status' => RepayRecord::FAILURE_STATUS_ONE,
                'failure_message' => $data['resultRemark'],
            ];
            $month->record()->where('id', $month->record_id)->update($record);
            //用户全局状态变更
            UserGlobal::where('uid', $month->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_FAILURE]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new GeneralException($e->getMessage());
        }
        return true;
    }
}